import { NextResponse } from 'next/server';
import prisma from '@/lib/prisma';

export async function GET() {
    try {
        const todayDishes = await prisma.dish.findMany({
            where: {
                isToday: true
            },
            select: {
                id: true,
                name: true,
                image: true,
                price: true,
                description: true,
                tags: true
            }
        });

        // 处理 tags 字段
        const formattedDishes = todayDishes.map(dish => ({
            ...dish,
            tags: typeof dish.tags === 'string' ? JSON.parse(dish.tags) : []
        }));

        return NextResponse.json(formattedDishes);
    } catch (error) {
        console.error('获取今日菜品失败:', error);
        return NextResponse.json(
            { error: '获取今日菜品失败' },
            { status: 500 }
        );
    }
}

export async function PUT(request: Request) {
    try {
        const { dishIds } = await request.json();
        
        // 先将所有菜品的 isToday 设置为 false
        await prisma.dish.updateMany({
            where: {},
            data: {
                isToday: false
            }
        });

        if (dishIds && dishIds.length > 0) {
            // 将选中的菜品设置为今日菜品
            await prisma.dish.updateMany({
                where: {
                    id: {
                        in: dishIds
                    }
                },
                data: {
                    isToday: true
                }
            });
        }

        return NextResponse.json({ message: '更新今日菜品成功' });
    } catch (error) {
        console.error('更新今日菜品失败:', error);
        return NextResponse.json(
            { error: '更新今日菜品失败' },
            { status: 500 }
        );
    }
} 